package xtask;

import jobs.annotations.JobInfo;
import org.apache.commons.lang.StringUtils;
import play.Play;
import play.jobs.Every;
import play.jobs.On;
import play.jobs.OnApplicationStart;
import play.jobs.OnApplicationStop;
import utils.xtask.XTaskService;

/**
 * @author zhangzc
 * @since 5/18/18
 */
public class XTaskBean {

    public Class clazz;

    public String className;

    /**
     * 名称
     */
    public String name;

    /**
     * 执行计划
     */
    public String schedule;

    /**
     * 运行时间阈值
     */
    public String deadline;

    public long executeCount = 0;

    /**
     * 上次执行的开始时间，单位毫秒
     */
    public long lastExecuteTime = 0l;

    /**
     * 上次执行的时长，单位毫秒
     */
    public Long lastExecuteDuration = 0l;

    /**
     * 上次执行的进度，0-100
     */
    public int lastExecuteProgress = 0;

    public XTaskBean(Class jobClass){
        this.clazz = jobClass;
        this.className = jobClass.getSimpleName();

        JobInfo jobInfo = (JobInfo) jobClass.getAnnotation(JobInfo.class);
        if(jobInfo != null){
            this.className = jobInfo.name();
            this.name = jobInfo.desc();
            this.deadline = jobInfo.deadline();
        }

        //初始化schedule
        OnApplicationStart onApplicationStart = (OnApplicationStart) jobClass.getAnnotation(OnApplicationStart.class);
        if(onApplicationStart != null){
            this.schedule = "启动时执行";
        }

        OnApplicationStop onApplicationStop = (OnApplicationStop) jobClass.getAnnotation(OnApplicationStop.class);
        if(onApplicationStop != null){
            this.schedule = "关闭时执行";
        }

        Every every = (Every)jobClass.getAnnotation(Every.class);
        if(every != null){
            this.schedule = "周期执行："+every.value();
        }

        On on = (On)jobClass.getAnnotation(On.class);
        if(on != null){
            this.schedule = "定时执行："+on.value();
        }

        //lastExecuteTime
        this.lastExecuteTime = XTaskService.getTime(jobClass.getName(), "start");
        //executeCount
        this.executeCount = XTaskService.getExecuteCount(jobClass.getName());
        //lastExecuteDuration
        long lastExecuteEndTime = XTaskService.getTime(jobClass.getName(), "end");
        if(lastExecuteEndTime > 0 && lastExecuteEndTime > this.lastExecuteTime){
            this.lastExecuteDuration = lastExecuteEndTime - this.lastExecuteTime;
        }else{
            this.lastExecuteDuration = null;
        }

    }

    public String getDisplayName(){
        return StringUtils.isEmpty(this.name) ? this.className : this.name;
    }

}
